package com.io.convert;



import java.io.*;

/**
 *
 * @author jiangbang
 * @date 2016/6/3
 */
public class ByteArrayDemo2 {
    public static void main(String[] args) throws IOException {
        byte[] data = getBytesFromFile("D:/demo/1.txt");
        toFileByteArray(data,"D:/demo/2.txt");
        System.out.println(new String(data));
    }


    /**
     *2.字节数组 --程序 -- 文件
     */
    public static void toFileByteArray(byte[] src,String path) throws IOException {
        //目的地
        File file = new File(path);
        //选择流
        //字节数组输入流
        InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
        //文件输出流
        OutputStream os = new BufferedOutputStream(new FileOutputStream(file, true));

        byte[] flush = new byte[1024];
        int len = 0 ;
        while(-1!=(len=is.read(flush))){
            os.write(flush,0,len);
        }
        os.flush();
        os.close();
        is.close();
    }





    /**
     * 1.文件 --》程序 --》字节数组
     * @param path
     * @return
     * @throws IOException
     */
    public static byte[] getBytesFromFile(String path) throws IOException {
        File file = new File(path);
        //创建字节数组目的地
        byte[] dest = null;
        //选择流
        // 文件输入流
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        //字节数组输出流 不能使用多态
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte[] flush = new byte[1024];
        int len = 0 ;
        while(-1!=(len=is.read(flush))){
            bos.write(flush,0,len);
        }
        bos.flush();
        //获取数据
        dest = bos.toByteArray();
        bos.close();
        return dest;

    }
}
